package com.apes.fn.crm.customComplain;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.fileserver.File;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;

/**
 * 功能：客诉单
 *
 * @author Biebi
 * @create 2018-7-11 11:42:47
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = FnCustomComplain.CONST_TABLE_NAME)
public class FnCustomComplain extends Model {
    public static final String CONST_TABLE_NAME = "fn_custom_complain";

    @Id
    @Comment("客诉单号")
    @Column(name = "id", nullable = false, length = 120)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "客诉单号(赋能)", prefix = "K%(yy)%(month)", padding = 5, useDateRange = true)
    private String id;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;


    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null) return null;
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "vendorCode", customerExpand.getVendorCode(),
                "mobile", customerExpand.getMobile()
        );
    }

    public boolean isNoneCustomerCar() {
        return customerExpand==null || customerExpand.getMobile() == null;
    }

    @Transient
    private boolean noneCustomerCar;

    @Transient
    private Map customerCar;

    public Map getCustomerCar() {
        if (noneCustomerCar)return null;
        if (customerExpand == null || customerExpand.getCarLicense() == null) return null;
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer()
        );
    }

    @Comment("门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    private Dept dept;

    @Comment("客诉类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "custom_complain_type", referencedColumnName = "id")
    private Enumeration customComplainType;

    @Comment("客诉来源")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "custom_complain_source", referencedColumnName = "id")
    private Enumeration customComplainSource;

    @Comment("投诉类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "complain_type", referencedColumnName = "id")
    private Enumeration complainType;

    @Comment("投诉类别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "complain_category", referencedColumnName = "id")
    private Enumeration complainCategory;

    @Comment("投诉级别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "complain_level", referencedColumnName = "id")
    private Enumeration complainLevel;

    @Comment("投诉内容")
    @Column(name = "complain_content", length = 4000)
    private String complainContent;

    @Comment("处罚方案")
    @Column(name = "punishment_plan", length = 4000)
    private String punishmentPlan;


    @Comment("责任客诉")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "responsibility_complain", referencedColumnName = "id")
    private Enumeration responsibilityComplain;


    @Comment("被投诉人")
    @Column(name = "complain_persons", length = 4000)
    private String complainPersons;

    public void setComplainPersons(String complainPersons) {
    }

    @Transient
    private Set<PartyRole> cPersons;

    public Set<PartyRole> getcPersons() {
        if (isWrite() || isLoad()) {
            cPersons = getPersons(this.complainPersons);
        }
        return cPersons;
    }

    public void setcPersons(Set<PartyRole> cPersons) {
        this.cPersons = cPersons;
        if (!isWrite()) {
            this.complainPersons = toConvertPersons(this.cPersons);
        }
    }

    @Comment("责任人")
    @Column(name = "responsible_persons", length = 400)
    private String responsiblePersons;

    public void setResponsiblePersons(String responsiblePersons) {
    }

    @Transient
    private Set<PartyRole> rPersons;

    public Set<PartyRole> getrPersons() {
        if (isWrite() || isLoad()) {
            rPersons = getPersons(this.responsiblePersons);
        }
        return rPersons;
    }

    public void setrPersons(Set<PartyRole> rPersons) {
        this.rPersons = rPersons;
        if (!isWrite()) {
            this.responsiblePersons = toConvertPersons(this.rPersons);
        }
    }

    @Transient
    private Set<PartyRole> getPersons(String source) {
        if (StringUtil.isEmpty(source)) return null;
        Set<PartyRole> persons = new HashSet<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(PartyRoleRepository.class).findOne(String.valueOf(StringUtils.split(person, "|")[0])));
            }
        }
        return persons;
    }

    private String toConvertPersons(Set<PartyRole> persons) {
        StringBuffer sb = new StringBuffer();
        for (PartyRole party : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(party.getId());
            sb.append("|");
            sb.append(party.getName());  // 格式 id|name;
        }
        return sb.toString();
    }

    @Comment("服务单号")
    @Column(name = "server_id", length = 120)
    private String server;

    @Comment("跟踪人员")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tracer_id", referencedColumnName = "id")
    private PartyRole tracerId;

    // 业务部门
    @Comment("责任门店/部门(业务部门)")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "responsibility_dept_id", referencedColumnName = "id")
    private Dept responsibilityDept;


    @Comment("责任门店/部门(行政部门)")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "responsibility_branch_id", referencedColumnName = "id")
    private Branch responsibilityBranch;

    @Comment("责任组别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "responsibility_group", referencedColumnName = "id")
    private Enumeration responsibilityGroup;


    @Comment("客户满意度")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "custom_satisfaction", referencedColumnName = "id")
    private Enumeration customSatisfaction;


    @Comment("预计起单时间")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "start_date")
    private Date startDate;

    @Comment("启单人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "start_id", referencedColumnName = "id")
    private PartyRole startId;


    @Comment("实际启单时间")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "real_start_date")
    private Date realStartDate;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company; //

    @States(name = "单据状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "delete", name = "删除"),
            @State(id = "disposing", name = "客诉处理"),
            @State(id = "visiting", name = "客服回访"),
            @State(id = "transStop", name = "申请停单"),
            @State(id = "stop", name = "停单"),
            @State(id = "end", name = "结单")
    })
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @States(name = "活跃状态", values = {
            @State(id = "0", name = "挂起"),
            @State(id = "1", name = "激活"),
    })
    @Column(name = "active", nullable = false, columnDefinition = "number(1,0) default 1")
    private boolean active = true; // 活跃状态

    @Comment("删除人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    private PartyRole deleteId;

    @Comment("删除日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    private Date deleteDate;

    @Comment("oa发起人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "initiat_oa_id", referencedColumnName = "id")
    private PartyRole initiatOaId;

    @Comment("oa发起时间")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "initiat_oa_date")
    private Date initiatOaDate;

    @Comment("结单人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "end_id", referencedColumnName = "id")
    private PartyRole endId;


    @Comment("结单日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "end_date")
    private Date endDate;

    @Comment("责任分配人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "assign_id", referencedColumnName = "id")
    private PartyRole assignId;

    @Comment("责任分配日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "assign_date")
    private Date assignDate;

    @Comment("外部ID(用于记录原始的客诉单号)")
    @Column(name = "ORIGIN", length = 20)
    private String origin;

    @Comment("转停单人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "transtop_id", referencedColumnName = "id")
    private PartyRole transtopId;


    @Comment("转停单日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "transtop_date")
    private Date transtopDate;


    @Comment("停单人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "stop_id", referencedColumnName = "id")
    private PartyRole stopId;


    @Comment("停单日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "stop_date")
    private Date stopDate;


    @Comment("转客服回访人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "trans_visit_id", referencedColumnName = "id")
    private PartyRole transVisitId;

    @Comment("转客服回访日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "trans_visit_date")
    private Date transVisitDate;

    @Comment("客诉处理节点候选人")
    @Column(name = "next_dispose_sign", length = 120)
    private String nextDisposeSign;

    @File
    @Lob
    @Comment("图片")
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "imgs", columnDefinition = "CLOB")
    private String imgs;

    @Comment("处罚结果")
    @Column(name = "punishment_result", length = 4000)
    private String punishmentResult;

    @Comment("承担金额")
    @Column(name = "amount_assumed", length = 4000)
    private String amountAssumed;

    @Comment("单据来源")
    @Column(name = "source", length = 4000)
    private String source;


    @OneToMany(mappedBy = "fnCustomComplain", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<FnCustomComplainSource> fnCustomComplainSources = new HashSet();

    public Set<FnCustomComplainSource> getFnCustomComplainSources() {
        if (fnCustomComplainSources == null) return new HashSet();
        for (FnCustomComplainSource item : fnCustomComplainSources) {
            item.setFnCustomComplain(this);
        }
        return fnCustomComplainSources;
    }

    public void setFnCustomComplainSources(Set<FnCustomComplainSource> fnCustomComplainSources) {
        this.fnCustomComplainSources.clear();
        if (fnCustomComplainSources != null) {
            this.fnCustomComplainSources.addAll(fnCustomComplainSources);
        }
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
}
